<?php
declare (strict_types=1);

namespace app\api\controller\v1;

use app\api\helpers\v1\traits\FileUpload;
use app\api\helpers\v1\traits\SearchDataForModel;
use app\api\model\v1\AdminLog;
use app\api\model\v1\CollectionTopic;
use app\api\model\v1\Learn;
use app\api\model\v1\LearnTopic;
use app\api\model\v1\TopicExerciseLog;
use app\BaseController;
use think\Request;

class Study extends BaseController
{
    use SearchDataForModel, FileUpload;

    /**
     * @User: 刘海龙
     * @Date: 2021/10/8
     * @Time: 15:50
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 数据源
     */
    public function getStudyList()
    {
        $limit = $this->request->param('limit', 10);
        $res = $this->search(new Learn(), [], $limit);
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/10/8
     * @Time: 16:15
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 根据id获取对应的题目
     */
    public function getStudyTopicList()
    {
        $limit = $this->request->param('limit', 10);
        $learn_id = $this->request->param('learn_id', 0);
        $map[] = array('learn_id', '=', $learn_id);
        $res = $this->search(new LearnTopic(), $map, $limit, 'desc', ['option']);
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/10/8
     * @Time: 15:28
     * @return \think\response\Json
     * 导入学习考题
     */
    public function importStudyExcel()
    {
        if (!$this->request->file('file')) {
            return $this->response(501, '请选择上传文件');
        }
        $file = $this->request->file('file');
        $saveName = \think\facade\Filesystem::disk('public')->putFile('study_excel', $file);
        $path = app()->getRootPath() . 'public/storage/' . str_replace('\\', '/', $saveName);
        $returnData = $this->loadExcel($path);
        $data = $this->dataLearn($returnData);
        $is_bool = Learn::saveImportExcel($data, $this->request->uid);

        if ($is_bool === 200) {
            //日志
            AdminLog::record('导入学习答题', $this->request->param(), $this->request->uid, $this->request->username);
            return $this->response();
        } else if ($is_bool === 403) {
            return $this->response(403, '未找到学习开始模版');
        } else {
            return $this->response(403, '导入失败');
        }
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/10/9
     * @Time: 8:57
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 根据id 获取对应的题目
     */
    public function getTopicList()
    {
        $id = $this->request->param('id', 0);
        $res = Learn::find($id);
        if (is_null($res)) {
            return $this->response(403, '未找到相关题目');
        }
        $data = LearnTopic::field('id,topic_title as title,learn_id,learn_answer as answer,question_type as type,answer_explain')->with(['optionList' => function ($query) {
            $query->field('id,option_title as content,learn_topic_id');
            return $query;
        }])->where(['learn_id' => $id])->select()->each(function ($item, $key) {
            $item['userAnswer'] = "";
            $item['userFavor'] = false;
            return $item;
        })->toArray();
        return $this->response($data);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/10/9
     * @Time: 9:52
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 收藏
     */
    public function collectionTopic()
    {
        $data = $this->request->param();
        $topic_id = intval($data['topic_id']);
        $date_of = $data['date_of'];
        $res = CollectionTopic::where(['learn_topic_id' => $topic_id, 'collection_user_id' => $this->request->wx_id])->find();
        if (!is_null($res) && intval($data['is_collection']) !== 0) {
            return $this->response(403, '题目已经收藏,无需重复收藏');
        }
        if (intval($data['is_collection']) === 0) { //取消收藏
            CollectionTopic::destroy(function ($query) use ($topic_id, $date_of) {
                $query->where(['learn_topic_id' => $topic_id, 'collection_user_id' => $this->request->wx_id, 'date_of' => $date_of])->delete();
            }, true);
            $return_arr = [
                'type' => 'delete'
            ];
        } else { //收藏
            CollectionTopic::create([
                'learn_topic_id' => $data['topic_id'],
                'collection_user_id' => $this->request->wx_id,
                'date_of' => $date_of
            ]);
            $return_arr = [
                'type' => 'create'
            ];
        }
        return $this->response($return_arr);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/10/9
     * @Time: 12:04
     * @return \think\response\Json
     * @throws \Exception
     * 保存练习
     */
    public function saveTopic()
    {
        //题型：1判断题，2单选题，3多选题，4填空题，5问答题
        $data = $this->request->except(['version']);
        $logData = [];
        foreach ($data['data'] as $key => $value) {
            switch ($value['type']) {
                case 1: //判断题
                case 2://单选题
                    $optionListIndex = $value['answer'] - 1; //获取答案的索引
                    $answer_id = $value['optionList'][$optionListIndex]['id'];
                    $userAnswers = $value['userAnswer'];
                    if (intval($userAnswers) !== $answer_id) {
                        $is_error = 1; //错误
                    } else {
                        $is_error = 0; //正确
                    }
                    break;
                case 3: //多选题
                    $userAnswers = rtrim($value['userAnswer'], ',');
                    $answer_arr = explode(',', $value['answer']); //正确答案
                    $answer_ids = '';
                    //把索引转换为id字符串
                    foreach ($answer_arr as $k => $v) {
                        $answer_arr_key = intval($v) - 1;
                        $answer_ids .= $value['optionList'][$answer_arr_key]['id'] . ',';
                    }
                    $answer_id = rtrim($answer_ids, ',');
                    if ($userAnswers !== $answer_id) {
                        $is_error = 1; //错误
                    } else {
                        $is_error = 0; //正确
                    }
                    break;
                case 4: //4填空题
                case 5: //5问答题
                default: //其他
                    $is_error = 0; //正确
                    $userAnswers = $value['userAnswers'];
                    $answer_id = $value['answer'];
                    break;
            }
            $logData[] = [
                'learn_id' => $value['learn_id'],
                'title' => $value['title'],
                'learn_topic_id' => $value['id'],
                'answer' => $answer_id,
                'type' => $value['type'],
                'answer_explain' => $value['answer_explain'],
                'option' => json_encode($value['optionList'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
                'user_answer' => $userAnswers,
                'user_favor' => $value['userFavor'] === false ? 0 : 1,
                'show_answer' => $value['showAnswer'] === false ? 0 : 1,
                'is_error' => $is_error,
                'exercise_user_id' => $this->request->wx_id, //需要更改
                'date_of' => $data['date_of']
            ];
        }
        $log = new TopicExerciseLog();
        $log->saveAll($logData);
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/10/14
     * @Time: 18:11
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 数据列表
     */
    public function getTopicExerciseLog()
    {
        $data = $this->request->param();
        if (intval($data['idx']) === 0) {
            //答题记录
            $res = TopicExerciseLog::with(['option'])->where(['exercise_user_id' => $this->request->wx_id, 'date_of' => $data['date']])->select()->toArray();
        } else if (intval($data['idx']) === 1) {
            //错题记录
            $res = TopicExerciseLog::with(['option'])->where(['exercise_user_id' => $this->request->wx_id, 'date_of' => $data['date'], 'is_error' => 1])->select()->toArray();
        } else if (intval($data['idx']) === 2) {
            //收藏
            $res = CollectionTopic::with(['topic.option'])->where(['collection_user_id' => $this->request->wx_id, 'date_of' => $data['date']])->select()->each(function ($item, $key) {
                $answer = explode(',', $item['topic']['learn_answer']);
                $ids = '';
                foreach ($answer as $k => $v) {
                    $index = intval($v) - 1;
                    $ids .= $item['topic']['option'][$index]['id'] . ',';
                }
                $item['topic']['answer'] = rtrim($ids, ',');
                return $item;
            })->toArray();

        } else {
            //其他
            $res = [];
        }
        if (!empty($res)) {
            return $this->response($res);
        } else {
            return json(['code' => 400, 'data' => []]);
        }
    }


}
